<!DOCTYPE html>
<html>
<head>
<title>addRange failures</title>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script>
description('Test error handling of Selection.addRange().');

var selection = window.getSelection();

function testNull()
{
    shouldThrow('selection.addRange(null)');
}

function testEmptyRange()
{
    var range = new Range();
    selection.addRange(range);
}

function testNotInDocumentRange()
{
    var range = document.createRange();
    var notInDocument = document.createTextNode('not in document');
    range.selectNodeContents(notInDocument);
    selection.addRange(range);
}

function testOtherDocument()
{
    var iframe = document.createElement('iframe');
    document.body.appendChild(iframe);

    var range = iframe.contentDocument.createRange();
    selection.addRange(range);

    document.body.removeChild(iframe);
}

function testOtherDocumentFragments()
{
    var shadowHost = document.createElement('div');
    var shadowRoot = shadowHost.attachShadow({mode: 'open'});
    document.body.appendChild(shadowHost);

    var range = new Range();
    range.selectNodeContents(shadowRoot);
    selection.addRange(range);

    document.body.removeChild(shadowHost);
}

function runSingleTest(testFunction)
{
    selection.removeAllRanges();
    var range = new Range();
    range.setStart(document.body, 0);
    range.setEnd(document.body, 0);
    selection.addRange(range);

    debug('Running: ' + testFunction.name);
    testFunction(selection);

    // Selection should stay at the same position.
    shouldEvaluateTo('selection.rangeCount', 1);
    shouldBeTrue('selection.getRangeAt(0).startContainer === document.body');
    shouldEvaluateTo('selection.getRangeAt(0).startOffset', 0);
    shouldBeTrue('selection.getRangeAt(0).endContainer === document.body');
    shouldEvaluateTo('selection.getRangeAt(0).endOffset', 0);
}

var testFunctions = [testNull, testEmptyRange, testNotInDocumentRange, testOtherDocument, testOtherDocumentFragments];
testFunctions.forEach(runSingleTest);
</script>
</body>
</html>
